// 云函数入口文件
const cloud = require("wx-server-sdk");
cloud.init({
    throwOnNotFound: false,
});
const db = cloud.database({
    throwOnNotFound: false,
});
const $ = db.command;

// ! 在 transaction 里面 的 collection 不支持 where 查询操作

async function AuditXin(transaction, confirmXinDocs) {
    try {
        // 1. 取出需要确认的 UnPublicXin
        const mid = await Promise.all(
            confirmXinDocs.map((id) => {
                return transaction.collection("UnPublicXin").doc(id).get();
            })
        );
        // 2. 筛选出存在的 UnPublicXin 并生成 删除数组
        const [deleteResult, Removing] = mid.reduce(
            ([col, removing], i) => {
                if (i && i.data) {
                    col.push(i.data);
                    removing.push(
                        transaction
                            .collection("UnPublicXin")
                            .doc(i.data._id)
                            .remove()
                    );
                }
                return [col, removing];
            },
            [[], []]
        );

        // 3. 等待删除完成
        await Promise.all(Removing);

        await Promise.all(
            deleteResult.map(async (i) => {
                // 4. 更新在 PublicXin 中的重复项
                const id = i._id;
                delete i._id;
                return await transaction.collection("PublicXin").doc(id).set({
                    data: i,
                });
            })
        );

        return deleteResult;
    } catch (err) {
        // 会作为 runTransaction reject 的结果出去
        await transaction.rollback(err);
    }
}
// ! 调用人必为 Manager
exports.main = async (event, context) => {
    if (!event.confirmXinDocs)
        return {
            err: JSON.stringify(event),
            desc: "confirmXinDocs 属性不存在",
        };
    // ! 权限：调用人必为 Manager
    const { result: InvokerIsManager } = await cloud.callFunction({
        name: "isManager",
        data: {
            UserOpenId: event.userInfo.openId,
        },
    });
    if (InvokerIsManager !== true)
        return {
            err: "permission denied.\n" + JSON.stringify(InvokerIsManager),
            desc: "没有权限",
        };

    return db.runTransaction((transaction) =>
        AuditXin(transaction, event.confirmXinDocs)
    );
};
